package com.example.lenovo.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rlvStu;
    /*定义学生列表*/
    private ArrayList<Student> studentArrayList=new ArrayList<>();
    private ArrayList<Student> searchResultList=new ArrayList<>();
    private StuAdapter adapter;

    /*搜索框*/
    private EditText edtKeyword;
    private Button btnSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initStudentArrayList();

        initAdapter();

        initListView();

        initSearchView();

    }
/*初始化搜索模块*/
    private void initSearchView() {
        edtKeyword=findViewById(R.id.edt_keyword);
        btnSearch= findViewById(R.id.btn_search);

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyword = edtKeyword.getText().toString().trim();
                /*使用学生列表和关键早 得到搜索结果列表*/
                search(studentArrayList,keyword);
                adapter.changeDate(searchResultList);

            }
            /*使用学生列表和关键早 得到搜索结果列表*/
            private void search(ArrayList<Student> studentArrayList, String keyword) {
                searchResultList.clear();
                for(int i = 0;i<studentArrayList.size();i++){
                    Student s = studentArrayList.get(i);
                    //如果学生姓名包含了关键字 这个学生就加入到结果列表
                        if (s.getName().contains(keyword)){
                            searchResultList.add(s);
                        }
                }
            }
        });
    }

    /*初始化ListView*/
    private void initListView() {
        rlvStu= findViewById(R.id.rlv_stu);
        rlvStu.setAdapter(adapter);

        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
        rlvStu.setLayoutManager(manager);

    }

    /*初始化适配器*/
    private void initAdapter() {
        adapter=new StuAdapter(MainActivity.this,studentArrayList);
    }

    /*初始化学生列表*/
    private void initStudentArrayList() {
        Student s1 = new Student("18001","张三",20,R.drawable.timg1);
        Student s2 = new Student("18002","李四",23,R.drawable.timg2);
        Student s3 = new Student("18003","啦三",22,R.drawable.timg3);
        Student s4 = new Student("18004","娃娃",22,R.drawable.timg4);
        Student s5 = new Student("18005","丫丫",21,R.drawable.timg5);
        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);
        studentArrayList.add(s4);
        studentArrayList.add(s5);
    }
}
